//
//  MTCClienterViewController.m
//  ERP
//
//  Created by QA on 15/9/17.
//  Copyright (c) 2015年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MTCClienterViewController.h"
#import "MJRefresh.h"
#import "UITableView+Custom.h"

#import "MTCClienterViewCell.h"
#import "MTCCraeteClienterViewController.h"
#import "MTCClienterDetailViewController.h"

#import "NSDictionary+DataFormat.h"
#import "WebServiceCommonRequest.h"

@interface MTCClienterViewController ()<UISearchBarDelegate,UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate>

@property (strong, nonatomic) NSMutableArray *resultData;
@property (strong, nonatomic) NSMutableArray *searchListData;

@end

@implementation MTCClienterViewController
@synthesize searchDisplayController;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"客户资料"];
        UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"新增" style:UIBarButtonItemStyleDone target:self action:@selector(createClienterSelector:)];
        self.navigationItem.rightBarButtonItem = leftButton;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.resultData = [NSMutableArray array];
    self.searchListData = [NSMutableArray array];
    self.tableView.tableFooterView= [[UIView alloc] init];
    
    [self addUISearchBar];
    [self setupRefresh];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.edgesForExtendedLayout = UIRectEdgeBottom | UIRectEdgeLeft | UIRectEdgeRight;
}

//添加搜索框
- (void)addUISearchBar
{
    self.searchbar.placeholder = @"客户搜索";
    self.searchbar.autocorrectionType = UITextAutocorrectionTypeNo;
    self.searchbar.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.searchbar.delegate = self;//设置代理
    self.searchbar.backgroundColor = [UIColor colorWithRed:230/255.00 green:230/255.00 blue:230/255.00 alpha:0.80];
    
    self.searchbar.tintColor  = [UIColor whiteColor];
    self.searchbar.barTintColor = ThemeColorBlue;
    [self.searchbar setBackgroundImage:[UIImage new]];
    self.searchDisplayController.searchResultsTableView.tableFooterView = [[UIView alloc] init];
}

- (void)setupRefresh
{
    //添加下拉加载数据
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    [self.tableView headerBeginRefreshing];
    [self.tableView footerEndRefreshing];
}

- (void)stopRefresh
{
    //移除下拉加载数据
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
}

#pragma mark UISearchBarDelegate

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
{
    if (!(searchText && searchText.length > 0)) return;
    [searchDisplayController.searchResultsTableView reloadData];
    [self getSearchNetWorkDataText:searchText];
}

- (void)getSearchNetWorkDataText:(NSString*)searchText
{
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"KHDA_KHLB_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"起始条数" value:@0];
    [content addParameterKey:@"结束条数" value:@100];
    [content addParameterKey:@"检索条件" value:searchText];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        [self.searchListData removeAllObjects];
        if(firstArray && firstArray.count>0){
            [self.searchListData addObjectsFromArray:firstArray];
            [searchDisplayController.searchResultsTableView reloadData];
        } else{
            searchDisplayController.searchResultsTitle = @"未找到客户";
            [searchDisplayController.searchResultsTableView reloadData];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self.searchListData removeAllObjects];
        searchDisplayController.searchResultsTitle = @"哦，出错了";
        [searchDisplayController.searchResultsTableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self.searchListData removeAllObjects];
        searchDisplayController.searchResultsTitle = @"无法连接网络";
        [searchDisplayController.searchResultsTableView reloadData];
    }];
    
}

#pragma mark 网络获取数据

- (void)getNetWorkDataIsReresh:(BOOL)isReresh state:(NSNumber*)state end:(NSNumber*)end
{
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"KHDA_KHLB_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"起始条数" value:state];
    [content addParameterKey:@"结束条数" value:end];
    [content addParameterKey:@"检索条件" value:@""];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(isReresh) [self.tableView headerEndRefreshing];
        else [self.tableView footerEndRefreshing];
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(isReresh) [self.resultData removeAllObjects];
        if(firstArray && firstArray.count>0){
            [self.resultData addObjectsFromArray:firstArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView reloadData];
        } else if(isReresh){
            [self.tableView setTableViewNotDataDrawText:@"暂无客户" isShow:YES];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"无法连接网络"];
    }];
    
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:0];
    NSNumber *endNumber = [NSNumber numberWithInteger:10];
    [self getNetWorkDataIsReresh:YES state:stateNumber end:endNumber];
}

- (void)footerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:self.resultData.count + 1];
    NSNumber *endNumber = [NSNumber numberWithInteger:self.resultData.count + 10];
    [self getNetWorkDataIsReresh:NO state:stateNumber end:endNumber];
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == searchDisplayController.searchResultsTableView) {
        return self.searchListData.count;
    } else {
        return self.resultData.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifierOne = @"MTCClienterViewCell";
    MTCClienterViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierOne];
    if (!cell)
        cell = [[MTCClienterViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierOne];
    
    NSDictionary *dictionary = nil;
    if (tableView == searchDisplayController.searchResultsTableView){
        dictionary = [self.searchListData objectAtIndex:indexPath.row];
    } else {
        dictionary = [self.resultData objectAtIndex:indexPath.row];
    }
    
    cell.clienterNumber.text = [dictionary objectFormatStringForKey:@"客户编号" defaults:@"无客户编号"];
    cell.clienterName.text = [dictionary objectFormatStringForKey:@"客户名称" defaults:@"无客户名称"];
    cell.clienterAddress.text = [dictionary objectFormatStringForKey:@"注册地" defaults:@"未知"];
    cell.starView.starNumber = [dictionary objectFormatIntegerForKey:@"客户星级"];
    
    return cell;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 78;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dictionary = nil;
    if (tableView == searchDisplayController.searchResultsTableView){
        dictionary = [self.searchListData objectAtIndex:indexPath.row];
    } else {
        dictionary = [self.resultData objectAtIndex:indexPath.row];
    }
    
    MTCClienterDetailViewController *viewController = [[MTCClienterDetailViewController alloc] initWithValue:dictionary];
    viewController.backResultDelagate = self;
    viewController.key = @"ModifProject";
    [self.navigationController pushViewController:viewController animated:YES];
}


#pragma mark -
#pragma mark Button Selector

- (void)createClienterSelector:(id)sender
{
    MTCCraeteClienterViewController *viewController = [[MTCCraeteClienterViewController alloc] init];
    viewController.backResultDelagate = self;
    viewController.key = @"CreateProject";
    [self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark -
#pragma mark BackResultDataDelagate

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    if (!backValue) return;
    
    //新增工程
    if ([key isEqualToString:@"CreateProject"]) {
        NSDictionary *valueDic = backValue;
        [self.resultData insertObject:valueDic atIndex:0];
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self.tableView reloadData];
        
    } else if ([key isEqualToString:@"ModifProject"]) {
        //修改工程
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        NSInteger index = [self.resultData indexOfObject:originalArray[0]];
        if(index > self.resultData.count){
            [self.resultData insertObject:originalArray[1] atIndex:0];
        } else {
            [self.resultData removeObjectAtIndex:index];
            [self.resultData insertObject:originalArray[1] atIndex:index];
        }
        
        [self.tableView reloadData];
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无客户信息" isShow:YES];
    }
}


@end

